package com.jinzhi.jzweb.service.resourceLibrary.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.PasswdUtils;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.common.utils.UUIDUtils;
import com.jinzhi.jzweb.dao.resourceLibrary.EventResourceClassMapper;
import com.jinzhi.jzweb.dao.resourceLibrary.EventResourceStatisticMapper;
import com.jinzhi.jzweb.domain.StuClassDO;
import com.jinzhi.jzweb.domain.StudentClassesDO;
import com.jinzhi.jzweb.domain.vo.resourceLibrary.eventresourceVO.ClassesVO;
import com.jinzhi.jzweb.domain.vo.resourceLibrary.eventresourceVO.PageResult;
import com.jinzhi.jzweb.domain.vo.resourceLibrary.eventresourceVO.StudentDetailVO;
import com.jinzhi.jzweb.domain.vo.resourceLibrary.eventresourceVO.StudentVO;
import com.jinzhi.jzweb.service.resourceLibrary.EventResourceClassService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName EventResourceClassServiceImpl
 * @Description:
 * @Author: ak
 * @CreateDate: 2024/5/11 10:10
 * @UpdateUser:
 * @UpdateDate: 2024/5/11 10:10
 * @UpdateRemark:
 * @Version: 1.0
 */
@Service("EventResourceClassService")
public class EventResourceClassServiceImpl extends ServiceImpl<EventResourceClassMapper, StudentClassesDO>
        implements EventResourceClassService {

    @Resource
    private EventResourceClassMapper classMapper;
    @Resource
    private UserService userService;
    @Resource
    private EventResourceStatisticMapper statisticMapper;


    @Override
    public PageResult list(String classname, String name, String mobile, Integer pageNum, Integer pageSize) {
        Long userId = null;
        if (StrUtil.isNotBlank(name) || StrUtil.isNotBlank(mobile)) {
            //根据姓名或手机号查询到用户id
            EntityWrapper<UserDO> userDOEntityWrapper = new EntityWrapper<>();
            userDOEntityWrapper.like(StrUtil.isNotEmpty(name), "name", name);
            userDOEntityWrapper.like(StrUtil.isNotEmpty(mobile), "mobile", mobile);
            UserDO userDO = userService.selectOne(userDOEntityWrapper);
            userId = userDO.getId();
        }

        // 根据用户id 和班级查询
        int start = (pageNum - 1) * pageSize;
        int end = start + pageSize;
        List<ClassesVO> classList = classMapper.getClasses(classname, userId, start, end);

        return new PageResult(classList.size(), classList);
    }

    @Override
    public List<String> classList() {
        return classMapper.classList();
    }

    @Transactional
    @Override
    public Result batchSaveClass(String classname, String creatername, List<StudentVO> studentVOList) {
        Result<String> result = new Result<>();

        Long userId = ShiroUtils.getUserId();
        UserDO userDO = userService.selectById(userId);

        if (ObjectUtil.isEmpty(userDO)) {
            result.setCode(1);
            result.setMsg("请重新登录");
            return result;
        }

        StudentClassesDO studentClassesDO = new StudentClassesDO();
        studentClassesDO.setName(classname);
        studentClassesDO.setCreaterDate(DateTime.now());
        studentClassesDO.setCreaterId(userDO.getId());
        studentClassesDO.setOrgId(userDO.getOrgId());
        studentClassesDO.setIsDelete(1);
        studentClassesDO.setUpdaterId(null);
        studentClassesDO.setThumbnail(null);
        studentClassesDO.setDescribe(userDO.getName() + "后台添加班级");


        // 不能创建同名班级
        Long classId = classMapper.getClassId(userDO.getId(), classname);
        if (classId == null) {
            classMapper.insert(studentClassesDO);
        } else {
            // 存在被删除则恢复
            classMapper.reCreateClass(classId, DateTime.now().toString());
        }

        // 添加学生到用户表
        for (StudentVO studentVO : studentVOList) {

            // 手机号重复判断
            UserDO userDuplication = new UserDO();
            userDuplication.setMajor(studentVO.getMobile());
            // 手机号重复判断
            UserDO existUser = null;
            try {
                existUser = userService.getMobile(studentVO.getMobile());
            }catch (Exception e) {
                result.setCode(1);
                result.setMsg("存在多个相同手机号 请联系管理员");
                return result;
            }

            if (ObjectUtil.isNotNull(existUser)) {
                StringBuffer sb = new StringBuffer();
                result.setCode(1);
                result.setMsg(sb.append(studentVO.getName()).append("手机号已存在！").toString());
                return result;
            }

            UserDO user = new UserDO();
            user.setName(studentVO.getName());
            user.setUsername(studentVO.getMobile());
            // 前端传输字段username == mobile
            user.setMobile(studentVO.getMobile());
            user.setSex(Long.valueOf(studentVO.getSex()));
            // 密码 加盐
            user.setSalt(UUIDUtils.get());
            user.setPassword(PasswdUtils.get("123456", user.getSalt()));

            user.setGmtCreate(DateTime.now());
            user.setUserIdCreate(userDO.getId());
            // 用户新增来源 1 金职资源库添加学生
            user.setUserFrom(1);
            // 0个人会员为学生 1机构会员为老师 2运营会员为讲师
            user.setType(0);
            classMapper.saveUser(user);
            Long insertUserId = classMapper.getInsertUserId(user);
            studentVO.setId(insertUserId);
        }

        // 添加学生列表
        ArrayList<StuClassDO> stuClassDOList = new ArrayList<>();
        for (StudentVO studentVO : studentVOList) {

            StuClassDO stuClassDO = new StuClassDO();
            stuClassDO.setUserId(studentVO.getId());
            stuClassDO.setAddTime(DateTime.now());
            stuClassDO.setClassId(classId);
            stuClassDO.setExamineDate(DateTime.now());
            stuClassDO.setIsDelete(1);
            stuClassDO.setType(0);

            // 教师添加学生时 默认审核状态为已通过
            stuClassDO.setStatus(1);
            stuClassDO.setDescribe(userDO.getName() + "用户添加的学生");
            stuClassDOList.add(stuClassDO);
        }

        // 只保存班级
        if (stuClassDOList.size() == 0) {
            result.setCode(0);
            result.setMsg(EnumErrorCode.success.getMsg());
            return result;
        }
        // 保存班级和学生表
        boolean b = classMapper.batchSaveStuClass(stuClassDOList);
        if (b == true) {
            result.setCode(0);
            result.setMsg(EnumErrorCode.success.getMsg());
            return result;
        } else {
            result.setCode(1);
            result.setMsg(EnumErrorCode.fail.getMsg());
            return result;
        }

    }

    /**
     * @auther: ak
     * @Description 查看班级详情
     * @param:
     * @return:
     * @date: 2024/5/17 15:16
     */
    @Override
    public PageResult getClassDetails(Long classId, Integer pageNum, Integer pageSize) {
        //分页
        int start = (pageNum - 1) * pageSize;
        int end = start + pageSize;
        // 班级学生信息
        List<StudentVO> classDetailList = classMapper.getStudentInfo(classId, start, end);
        ClassesVO classesVO = classMapper.getClassById(classId);
        // 学习总时长 练题次数 练题总数量
        List<StudentDetailVO> studentDetailVOList = classDetailList.stream()
                .map(studentVO -> {
                    StudentDetailVO studentDetailVO = statisticMapper.personalPracticeCount(studentVO.getId());
                    BeanUtils.copyProperties(studentVO, studentDetailVO);
                    studentDetailVO.setClassId(classesVO.getId());
                    studentDetailVO.setClassname(classesVO.getName());
                    return studentDetailVO;
                }).collect(Collectors.toList());

        return new PageResult(studentDetailVOList.size(), studentDetailVOList);
    }

    @Override
    public boolean quitStu(Long userId, Long classId) {
        EntityWrapper<UserDO> userDOEntityWrapper = new EntityWrapper<>();
        userDOEntityWrapper.eq("id", userId);
        userService.delete(userDOEntityWrapper);
        return classMapper.quitStu(userId, classId);
    }

    @Override
    public boolean updateClass(Long classId, String className, Long userId) {
        return classMapper.updateClass(classId, className, userId, DateTime.now().toString());
    }

    @Override
    public boolean updateStu(String name, String mobile, Long sex, Long id, String password) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = dateFormat.format(date.getTime());
        UserDO oldUserDO = classMapper.getSysUserByUserId(id);

        // 传入密码不为空为修改密码请求
        if (StringUtils.isEmpty(name)) {
            name = oldUserDO.getName();
        }
        if (StringUtils.isEmpty(mobile)) {
            mobile = oldUserDO.getMobile();
        }
        if (sex == null) {
            sex = oldUserDO.getSex();
        }

        if (StringUtils.isEmpty(password)) {
            password = oldUserDO.getPassword();
        } else {
            // 生成新密码
            password = PasswdUtils.get(password, oldUserDO.getSalt());
        }

        return classMapper.updateStu(name, mobile, sex, password, oldUserDO.getId(), nowTime);
    }

    @Override
    public boolean isExistClass(String classname, Long userId) {
        Long isExistClass = classMapper.isExistClass(classname, userId);
        // 存在 返回true
        return isExistClass != null ? true : false;
    }

    @Override
    public ClassesVO getClassById(Long id) {
        return classMapper.getClassById(id);
    }

    @Override
    public StudentDetailVO getClassDetailById(Long userId) {
        StudentDetailVO studentDetailVO = statisticMapper.personalPracticeCount(userId);
        UserDO userDO = userService.getByUserId(userId);
        BeanUtils.copyProperties(userDO, studentDetailVO);
        return studentDetailVO;
    }

    @Override
    public boolean deleteClass(Long classId) {
        List<StuClassDO> stuClassList = classMapper.getStuClassById(classId);

        if (ObjectUtil.isNotNull(stuClassList)) {
            for (StuClassDO stuClassDO : stuClassList) {
                if (stuClassDO.getIsDelete() == 1) {
                    // 物理删除用户
                    userService.deleteById(stuClassDO.getUserId());
                    // 班级学生关联表也删除
                    classMapper.quitStu(stuClassDO.getUserId(), stuClassDO.getClassId());
                }
            }
        }
        return classMapper.deleteClass(classId);
    }


}
